<script setup lang="ts">
import {ref, defineModel, watch, h, defineProps, defineEmits, nextTick} from 'vue';
import type {DataTableColumns} from 'naive-ui'
import {NButton, NSelect, NInput, NCheckbox} from 'naive-ui'
import {getXXColumnListAPI, updateXXColumnAPI} from '@/api/api.ts'

const showDrawer = defineModel('show', {type: Boolean, required: true})
const emits = defineEmits(['handleSubmit'])
const props = defineProps({
  tableName: {
    type: String
  }
})
// 表单数据
const submitLoading = ref<boolean>(false)
const contentLoading = ref<boolean>(false)
const timeStamp = ref<number>(0)
const rowKey = (row: RowData) => row.id;

interface Song {
  id: string
  field: string
  header: string
  type: string
  addable: string
  search: string
  searchType: string
  editable: string
  viewable: string
  hidden: string
  disabled: string
  required: string
  selecturl: string
}

const editorData = ref<RowData[]>([])

function createColumns({
                         play
                       }: {
  play: (row: Song) => void
}): DataTableColumns<Song> {
  return [
    {
      title: '序号',
      key: 'sequence',
      width: 80,
      align: 'center',
      render: (row) => {
        return h(NInput, {
          defaultValue: row.sequence,
          onUpdateValue: (value) => {
            row.sequence = value
          }
        }, {
          default: () => row.sequence
        })
      }
    },
    {
      title: '字段列名（field）',
      key: 'field',
      width: 150
    },
    {
      title: '字段描述（header）',
      key: 'header',
      width: 170,
      render: (row) => {
        return h(NInput, {
          defaultValue: row.header,
          onUpdateValue: (value) => {
            row.header = value
            console.log('row-editorData', editorData.value)
          }
        }, {
          default: () => row.header
        })
      }
    },
    {
      title: '类型（type）',
      key: 'type',
      width: 280,
      render: (row) => {
        return h(NSelect, {
          options: [
            {label: '输入框-text', value: 'text'},
            {label: '多行输入框-textarea', value: 'textarea'},
            {label: '密码-password', value: 'password'},
            {label: '数字-number', value: 'number'},
            {label: '带输入建议-autocomplete', value: 'autocomplete'},
            {label: '下拉框-select', value: 'select'},
            {label: '多选下拉框-multiSelect', value: 'multiSelect'},
            {label: '可编辑的下拉菜单-selectCanedit', value: 'selectCanedit'},
            {label: '级联选择下拉菜单-selectCascader', value: 'selectCascader'},
            {label: '单选框-radio', value: 'radio'},
            {label: '多选框-checkbox', value: 'checkbox'},
            {label: '年-year', value: 'year'},
            {label: '月-month', value: 'month'},
            {label: '年月日-date', value: 'date'},
            {label: '年月日时间-datetime', value: 'datetime'},
            {label: '年月日范围-daterange', value: 'daterange'},
            {label: '年月日时间范围-datetimerange', value: 'datetimerange'},
            {label: '取色器-colorPicker', value: 'colorPicker'},
            {label: '上传文件-upload', value: 'upload'},
            {label: '自定义-custom', value: 'custom'},
            {label: '富文本编辑器-editor', value: 'editor'},
          ],
          defaultValue: row.type,
          onUpdateValue: (value) => {
            console.log('value', value)
            row.type = value
            switch (value) {
              case 'selectCascader':
                row.selecturl = '/department/tree/data'
                break;
              default:
                row.selecturl = ''
                break;
            }
            // console.log('row-editorData', editorData.value)
          }
        }, {
          default: () => row.type
        })
      }
    },
    {
      title: '新增（addable）',
      key: 'addable',
      width: 110,
      align: 'center',
      render: (row) => {
        return h(NCheckbox, {
          defaultChecked: row.addable,
          checkedValue: '1',
          uncheckedValue: '0',
          onUpdateChecked: (value) => {
            row.addable = value
          }
        }, {
          default: () => ''
        })
      }
    },
    {
      title: '查询（search）',
      key: 'search',
      width: 100,
      align: 'center',
      render: (row) => {
        return h(NCheckbox, {
          defaultChecked: row.search,
          checkedValue: '1',
          uncheckedValue: '0',
          onUpdateChecked: async (value) => {
            row.search = value
            row.searchtype = 'like'
            timeStamp.value ++
          }
        }, {
          default: () => ''
        })
      }
    },
    {
      title: '（searchType）',
      key: 'searchtype',
      width: 130,
      align: 'center',
      render: (row) => {
        return h(NSelect, {
          options: [
            {label: 'exact', value: 'exact'},
            {label: 'like ', value: 'like '},
            {label: 'range ', value: 'range '},
          ],
          defaultValue: row.searchtype,
          onUpdateValue: (value) => {
            row.searchtype = value
            // console.log('row-editorData', editorData.value)
          }
        }, {
          default: () => row.searchtype
        })
      }
    },
    {
      title: '编辑（editable）',
      key: 'editable',
      width: 110,
      align: 'center',
      render: (row) => {
        return h(NCheckbox, {
          defaultChecked: row.editable,
          checkedValue: '1',
          uncheckedValue: '0',
          onUpdateChecked: (value) => {
            row.editable = value
          }
        }, {
          default: () => ''
        })
      }
    },
    {
      title: '查看（viewable）',
      key: 'viewable',
      width: 110,
      align: 'center',
      render: (row) => {
        return h(NCheckbox, {
          defaultChecked: row.viewable,
          checkedValue: '1',
          uncheckedValue: '0',
          onUpdateChecked: (value) => {
            row.viewable = value
          }
        }, {
          default: () => ''
        })
      }
    },
    {
      title: '隐藏（hidden）',
      key: 'hidden',
      width: 100,
      align: 'center',
      render: (row) => {
        return h(NCheckbox, {
          defaultChecked: row.hidden,
          checkedValue: '1',
          uncheckedValue: '0',
          onUpdateChecked: (value) => {
            row.hidden = value
          }
        }, {
          default: () => ''
        })
      }
    },
    {
      title: '是否可编辑（disabled）',
      key: 'disabled',
      width: 110,
      align: 'center',
      render: (row) => {
        return h(NCheckbox, {
          defaultChecked: row.disabled,
          checkedValue: '1',
          uncheckedValue: '0',
          onUpdateChecked: (value) => {
            row.disabled = value
          }
        }, {
          default: () => ''
        })
      }
    },
    {
      title: '必填项（required）',
      key: 'required',
      width: 110,
      align: 'center',
      render: (row) => {
        return h(NCheckbox, {
          defaultChecked: row.required,
          checkedValue: '1',
          uncheckedValue: '0',
          onUpdateChecked: (value) => {
            row.required = value
          }
        }, {
          default: () => ''
        })
      }
    },
    {
      title: '接口地址（selecturl）',
      key: 'selecturl',
      width: 250,
      render: (row) => {
        return h(NInput, {
          defaultValue: row.selecturl,
          onUpdateValue: (value) => {
            row.selecturl = value
          }
        }, {
          default: () => row.selecturl
        })
      }
    },
    /*{
      title: '操作',
      key: 'actions',
      fixed: 'right',
      render(row) {
        return h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: 'small',
              onClick: () => play(row)
            },
            {default: () => 'Play'}
        )
      }
    }*/
  ]
}

const columns = createColumns({
  play(row: Song) {
    message.info(`Play ${row.title}`)
  }
})
const pagination = {
  pageSize: 100
}

// 提交按钮点击事件
const onSure = () => {
  updateXXColumn()
}

// 取消按钮点击事件
const onCancel = () => {
  showDrawer.value = false
}

const getXXColumnList = async () => {
  contentLoading.value = true
  editorData.value = [];
  const res = await getXXColumnListAPI({
    tableName: props.tableName || ''
  })
  console.log(res)
  if (res.status === 200) {
    // 更新表单数据
    editorData.value = res.value?.data || []
  }
  contentLoading.value = false
}

// 提交按钮
const updateXXColumn = async () => {
  submitLoading.value = true
  const res = await updateXXColumnAPI(editorData.value)
  console.log(res)
  if (res.status === 200) {
    showDrawer.value = false
    emits('handleSubmit')
  }
  submitLoading.value = false
}

watch(showDrawer, (val) => {
  if (val) {
    // 打开抽屉时，重置表单数据
    getXXColumnList()
  }
})
</script>

<template>
  <n-drawer v-model:show="showDrawer" width="96%" placement="right" :close-on-esc="false" :mask-closable="false"
            :auto-focus="false">
    <n-drawer-content title="字段信息" closable>
      <n-data-table
          flex-height
          :bordered="true"
          :single-line="false"
          :columns="columns"
          :data="editorData"
          :pagination="pagination"
          :row-key="rowKey"
          :loading="contentLoading"
          :key="timeStamp"
      />

      <template #footer>
        <n-button size="small" type="info" :loading="submitLoading" @click="onSure">提交</n-button>
        <n-button size="small" @click="onCancel">取消</n-button>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<style scoped lang="scss">
:deep(.n-drawer-body) {
  display: flex;
  flex-direction: column;

  .n-data-table {
    height: 100%;
  }
}
</style>